import axios from "axios";
import {Message} from "element-ui";

axios.defaults.baseURL = 'http://localhost:8080/api/v1';

//配置请求拦截器
//如果已经登录，则携带token
axios.interceptors.request.use(function (config) {
    const  token = window.localStorage.getItem("token")
    if (token) {
        //将token放到请求头发送给服务器,将token放在请求头中
        config.headers = {'token':token};
    }
    return config
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

axios.interceptors.response.use(function (config){
    config.headers = {"Access-Control-Allow-Headers":"*"};
    return config;
})

/**
 * 响应结果处理
 * @param res
 */
 function toMessage(res){
    Message.closeAll();
    if (res.code!==200){
        Message({
            message: res.msg,
            type: 'error'
        })
    }
}

/**
 * get请求
 * @param url
 * @param param
 */
export async function getRequest(url, param) {
    //从后台获取图片
    if (url+''=='common/getCode'){
        const {data: res} = await axios.get(url, {responseType: 'arraybuffer'})
        return res;
    }
    //正常get请求
    const {data: res} = await axios.get(url, {params:param})
    toMessage(res);
    return res;
}

/**
 * post请求
 * @param url
 * @param param
 * @returns {Promise<unknown>}
 */
export async function postRequest(url, param) {
    const {data: res} = await axios.post(url,param);
    toMessage(res);
    return res;
}

/**
 * put请求
 * @param url
 * @param param
 * @returns {Promise<any>}
 */
export async function putRequest(url,param) {
    const {data: res} = await axios.put(url,param);
    toMessage(res);
    return res;
}

/**
 * delete请求
 * @param url
 * @param param
 * @returns {Promise<any>}
 */
export async function deleteRequest(url,param){
    //正常get请求
    const {data: res} = await axios.delete(url, {params: param})
    toMessage(res);
    return res;
}

export async function patchRequest(url,param){
    const {data: res} = await axios.patch(url, {param})
    toMessage(res);
    return res;
}

export async function UploadRequest(url,file){
    let param = new FormData();
    param.append('file',file,file.name);
    let config = {
        headers:{'Content-Type':'multipart/form-data'}
    };  //添加请求头
    const {data: res} = await axios.post(url,param,config);
    toMessage(res);
    return res;
}
